package com.qianji.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.github.pagehelper.util.StringUtil;
import com.qianji.utils.QrCodeUtil;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author 钟丽诗
 * @Date 2021.3.29
 */
@Slf4j
@RequestMapping("/qrCode/")
@RestController
public class QrCodeUploadController {

    /**
     * OSS地域节点
     */
    @Value("${oss.endPoint}")
    private String endPoint;

    /**
     * 秘钥
     */
    @Value("${oss.accessKeyId}")
    private String accessKeyId;

    /**
     * 密匙
     */
    @Value("${oss.accessKeySecret}")
    private String accessKeySecret;

    /**
     * bucket名称
     */
    private String bucketName = "qianji-qrcode";

    /**
     * 文件夹名称
     */
    private String folderName = "image/";

    @ApiOperation("生成二维码并将二维码图片上传到OSS")
    @RequestMapping(value = "upload", method = RequestMethod.POST)
    public Map<String, Object> upload(String linkUrl,String fileName){
        OSS ossClient = null;
        Map<String, Object> resultMap = new HashMap<>();
        if(StringUtil.isEmpty(fileName)){
            resultMap.put("code",500);
            resultMap.put("message","请输入图片名称！！！");
            return resultMap;
        }
        try {
            //不含Logo
            QrCodeUtil.encode(linkUrl, null, "D:\\qrcode\\", "qrcode", true);
            File file = new File("D:\\qrcode\\qrcode.png");
            InputStream inputStream = new FileInputStream(file);
            fileName = folderName + fileName+ ".png";
            ossClient = new OSSClientBuilder().build(endPoint,accessKeyId,accessKeySecret);

            PutObjectRequest request  = new PutObjectRequest(bucketName,fileName,inputStream);

            log.info("request:{}",request.getFile());

            ossClient.putObject(request);

            String url = "https://"+bucketName+"."+endPoint+"/"+fileName;

            resultMap.put("code",200);
            resultMap.put("url",url);
            resultMap.put("message","图片上传成功");
            file.delete();

        }catch (Exception e){
            resultMap.put("code",500);
            resultMap.put("message","图片上传失败");
            e.printStackTrace();
        }finally {
            ossClient.shutdown();
        }
        return resultMap;
    }



}
